﻿namespace YK.Console.Business.RolePermissionGroups;

internal class SaveRolePermissionGroupHandler(IRepository<RolePermissionGroup> _repo) : IRequestHandler<SaveRolePermissionGroupRequest, bool>
{
    public async Task<bool> Handle(SaveRolePermissionGroupRequest request, CancellationToken cancellationToken)
    {
        await _repo.DeleteAsync(x => x.RoleId == request.RoleId, cancellationToken);

        if (request.PermissionGroupIds.Any())
        {
            var rolePermissionGourps = request.PermissionGroupIds.Select(x => new RolePermissionGroup
            {
                RoleId = request.RoleId,
                PermissionGroupId = x
            }).ToList();

            await _repo.AddRangeAsync(rolePermissionGourps, cancellationToken);
        }

        return true;
    }
}
